126. 单词接龙 II
为保证权益,题目请参考 126. 单词接龙 II(From LeetCode).
解决方案1
CPP
C++
//
// Created by lenovo on 2020/6/7.
//
#include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>
using namespace std;
const int INF = 1 << 20;
class Solution {
private:
unordered_map<string, int> wordId;
vector<string> idWord;
vector<vector<int>> edges;
public:
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string> &wordList) {
int id = 0;
for (const string &word : wordList) {
if (!wordId.count(word)) {
wordId[word] = id++;
idWord.push_back(word);
}
}
if (!wordId.count(endWord)) {
return {};
}
if (!wordId.count(beginWord)) {
wordId[beginWord] = id++;
idWord.push_back(beginWord);
}
edges.resize(idWord.size());
for (int i = 0; i < idWord.size(); i++) {
for (int j = i + 1; j < idWord.size(); j++) {
if (transformCheck(idWord[i], idWord[j])) {
edges[i].push_back(j);
edges[j].push_back(i);
}
}
}
const int dest = wordId[endWord];
vector<vector<string>> res;
queue <vector<int>> q;
vector<int> cost(id, INF);
q.push(vector<int>{wordId[beginWord]});
cost[wordId[beginWord]] = 0;
while (!q.empty()) {
vector<int> now = q.front();
q.pop();
int last = now.back();
if (last == dest) {
vector<string> tmp;
for (int index : now) {
tmp.push_back(idWord[index]);
}
res.push_back(tmp);
} else {
for (int i = 0; i < edges[last].size(); i++) {
int to = edges[last][i];
if (cost[last] + 1 <= cost[to]) {
cost[to] = cost[last] + 1;
vector<int> tmp(now);
tmp.push_back(to);
q.push(tmp);
}
}
}
}
return res;
}
bool transformCheck(const string &str1, const string &str2) {
int differences = 0;
for (int i = 0; i < str1.size() && differences < 2; i++) {
if (str1[i] != str2[i]) {
++differences;
}
}
return differences == 1;
}
};
int main() {
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89